package com.jltx.xq.relaxnewspro.utils;

import android.content.Context;
import android.text.TextUtils;

import com.jltx.xq.relaxnewspro.framework.App;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * Created by bo on 2017/5/1.
 */

public class Utils {

    private static Context  mContext = App.getApp().getApplicationContext();
    public static InputStream readFileFromRaw(int fileID){
        return mContext.getResources().openRawResource(fileID);
    }

    public static Document getDocmentByIS(InputStream is){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        Document doc = null;
        try{
            builder = factory.newDocumentBuilder();
        }catch (ParserConfigurationException e){
            e.printStackTrace();
        }
        try {
            doc = builder.parse(is);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return doc;
    }

    public static String RegexFind(String regex,String string){
        return RegexFind(regex, string, 1, 1);
    }

    public static String RegexFind(String regex,String string,int start,int end){
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(string);
        String res = string;
        while (matcher.find()){
            res = matcher.group();
        }
        return res.substring(start, res.length() - end);
    }

    public static String RegexReplace(String regex,String string,String replace){
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(string);
        return matcher.replaceAll(replace);
    }

    public static boolean hasString(String str){
        if(str == null || str.equals("")) {
            return false;
        }
        return true;
    }

    public static void getRawHtmlFromUrl(String url, Callback callback){
        if(callback == null || TextUtils.isEmpty(url)){
            return;
        }
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        Request request = builder.build();
        HttpUtil.enqueue(request, callback);
    }
}
